<template>
  <div>
    <el-form
      label-position="left"
      label-width="90px"
      ref="formRef"
      v-model="form"
    >
      <el-form-item label="条件类型">
        <el-radio-group v-model="form.itemType" @change="handleRuleTypeChange">
          <el-radio
            v-for="(item, index) in DIC_PROP.VAL_TYPE.slice(0, 3)"
            :key="index"
            :value="item.value"
            :label="item.label"
          />
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="form.itemType === '1'" label="动态表达式">
        <el-input
          v-model="form.dynamicExpression"
          class="input-attr"
          clearable
        />
        <el-tooltip placement="top">
          <template #content>
            表达式必须符合SpEL格式,如(0<#applyNum &&
            #applyNum>=3),其中#applyNum(表示从表单中获取applyNum列值,等同于#flowform.applyNum),
            除了#flowform,系统还支持#flowvar(流程变量)、#currentuser(当前用户)
          </template>
          <el-icon style="margin-left: 10px"><QuestionFilled /></el-icon>
        </el-tooltip>
      </el-form-item>
      <el-form-item v-if="form.itemType === '2'" label="动态函数">
        <CommonSelect
          v-model:defaultValue="form.dynamicFunctionId"
          placeholder="请选择动态函数"
          autoQuery
          label="functionName"
          value="id"
          url="/esflow/rule/function/getlist"
          @change="handleFunctionChange"
          :width="300"
        />
      </el-form-item>
      <el-form-item v-if="form.itemType === '2'">
        <template #label>
          <div class="flex flex-row items-center">
            <span>函数参数</span>
            <el-tooltip placement="top">
              <template #content>
                表达式必须符合SpEL格式,如(0<#applyNum &&
                #applyNum>=3),其中#applyNum(表示从表单中获取applyNum列值,等同于#flowform.applyNum),
                除了#flowform,系统还支持#flowvar(流程变量)、#currentuser(当前用户)
              </template>
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>
        <div
          v-for="(item, index) in form.dynamicFunctionParams"
          :key="index"
          class="flex flex-row items-center"
        >
          <el-text style="width: 100px">{{ item.paramLabel }}</el-text>
          <el-input v-model="item.paramValue" class="input-attr" type="text" />
        </div>
      </el-form-item>
      <el-form-item label="表单字段" v-if="form.itemType === '0'" prop="varKey">
        <el-select
          v-model="form.varKey"
          clearable
          filterable
          @change="handleSimpleItemChange"
        >
          <el-option
            v-for="(item, index) in props.formItemList"
            :key="index"
            :label="getFormItemLabel(item)"
            :value="getFormItemKey(item)"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="运算符"
        v-if="form.itemType === '0'"
        prop="varOperator"
      >
        <el-select v-model="form.varOperator" clearable>
          <el-option
            v-for="(item, index) in data.operatorOptions"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="校验值" v-if="form.itemType === '0'">
        <el-input v-model="form.varValue" clearable />
      </el-form-item>
    </el-form>
    <div style="display: flex; justify-content: center">
      <el-button
        type="primary"
        round
        style="width: 200px; margin-top: 10px; margin-bottom: 10px"
        @click="save()"
      >
        保存
      </el-button>
    </div>
  </div>
</template>
<script setup lang="ts" name="RuleGroupItem">
import { useMessage } from "@/hooks/message";
import { DIC_PROP } from "@/views/design/process/Dict";
import { getRandNodeId } from "@/utils/process";
import { validateNull } from "@/utils/validate";
import { PropType, onMounted, reactive, ref } from "vue";
import { getFormItemLabel, getFormItemKey } from "@/views/design/form/FormItem";
import type { FormItemPerm } from "@/views/design/form/FormComponentMixin";
import type { RuleGroupItem } from "../../ProcessNodes";

const props = defineProps({
  formItemList: {
    type: Array as PropType<FormItemPerm[]>,
    default: [] as any[]
  }
});

const emits = defineEmits(["confirm"]);
const formRef = ref(null);

const form = reactive<RuleGroupItem>({
  code: getRandNodeId(),
  itemType: "0",
  varKey: "",
  varOperator: "",
  varValue: "",
  dynamicExpression: "",
  dynamicFunctionId: "",
  dynamicFunctionName: "",
  dynamicFunctionParams: []
});

const data = reactive({
  operatorOptions: []
});

onMounted(() => {
  data.operatorOptions = DIC_PROP.OPERATOR;
});

const show = row => {
  form.code = row.code;
  form.itemType = row.itemType;
  form.varKey = row.varKey;
  form.varOperator = row.varOperator;
  form.varValue = row.varValue;
  form.dynamicExpression = row.dynamicExpression;
  form.dynamicFunctionId = row.dynamicFunctionId;
  form.dynamicFunctionName = row.dynamicFunctionName;
  form.dynamicFunctionParams = row.dynamicFunctionParams;
};

const reset = () => {
  form.itemType = "0";
  form.varKey = "";
  form.varOperator = "0";
  form.varValue = "";
  form.dynamicExpression = "";
  form.dynamicFunctionId = "";
  form.dynamicFunctionName = "";
  form.dynamicFunctionParams = [];
};

const handleFunctionChange = (id, option) => {
  form.dynamicFunctionName = option.functionName;
  form.dynamicFunctionParams = option.params;
};

const handleSimpleItemChange = () => {
  if (form.varKey && form.varKey.includes(".")) {
    const varKeyValArray = form.varKey.split(".");
    const dots = varKeyValArray.length - 1;
    if (dots === 2) {
      const tableKey = varKeyValArray[1];
      const columnKey = varKeyValArray[2];
      const formItem = props.formItemList.find(
        item => item.tableKey === tableKey && item.columnKey === columnKey
      );
      //默认1：1
      let mainSubRadio = "0";
      if (!formItem) {
        mainSubRadio = formItem.mainSubRadio;
      }
      //子表映射关系为1:N
      if (mainSubRadio === "1") {
        data.operatorOptions = DIC_PROP.OPERATOR.slice(6);
      } else {
        data.operatorOptions = DIC_PROP.OPERATOR;
      }
    } else {
      data.operatorOptions = DIC_PROP.OPERATOR;
    }
  }
};

const save = () => {
  if (form.itemType === "0") {
    if (validateNull(form.varKey)) {
      useMessage().warning("请选择表单字段");
      return;
    }
    if (validateNull(form.varValue)) {
      useMessage().warning("请输入校验值");
      return;
    }
  } else if (form.itemType === "1") {
    if (validateNull(form.dynamicExpression)) {
      useMessage().warning("请输入动态表单时");
      return;
    } else if (!validateDynamicExpression()) {
      return;
    }
  } else if (form.itemType === "2") {
    if (validateNull(form.dynamicFunctionId)) {
      useMessage().warning("请选择动态函数");
      return;
    }
  }
  emits("confirm", form);
};

const handleRuleTypeChange = (type?) => {
  if (!type) {
    type = "0";
  }
  form.itemType = type;
  if (form.itemType === "0") {
    form.dynamicExpression = "";
    form.dynamicFunctionId = "";
    form.dynamicFunctionName = "";
    form.dynamicFunctionParams = [];
  } else if (form.itemType === "1") {
    form.varKey = "";
    form.varOperator = "0";
    form.varValue = "";
    form.dynamicFunctionId = "";
    form.dynamicFunctionName = "";
    form.dynamicFunctionParams = [];
  } else if (form.itemType === "2") {
    form.dynamicExpression = "";
    form.varKey = "";
    form.varOperator = "0";
    form.varValue = "";
  }
};

const validateDynamicExpression = () => {
  if (form.dynamicExpression.indexOf("#") === -1) {
    form.dynamicExpression = "";
    useMessage().warning("当选择动态表达式条件时, 动态表达式必须符合SpEL格式");
    return false;
  }
  return true;
};

defineExpose({
  show,
  reset
});
</script>

<style lang="scss" scoped>
@use "@/assets/style/design/flow-attr.scss";
</style>
